<template>
  <div>
    <div class="d-flex align-item-center mb-1">
      <div class="flex-grow-1 panel-title">客户分布</div>
      <button class="btn btn-sm btn-outline-primary" v-show="level > +orgLever + 1" @click="onback">
        <i class="fa fa-angle-double-left"></i>
        返回
      </button>
    </div>
    <el-echarts
      :option="option"
      ref="echarts"
      theme="green"
      @onInit="onInit"
      :height="240"
      :event-listener="{ click: onClick }"
    ></el-echarts>
  </div>
</template>
<script>
import { echartsXFormatter } from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
export default {
  components: {},
  props: {},
  data() {
    return {
      chart: {},
      option: null,
      level: 0,
      cityData: [],
      countyData: [],
      tableName: 'customer_distribute_view_db',
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user']),
    orgLever() {
      return +this.user.orgRegionLever
    },
  },
  watch: {},
  created() {
    this.getData()
  },
  mounted() {},
  methods: {
    onInit(chart) {
      this.chart = chart
    },
    async onClick(xIndex) {
      let code = ''
      if (this.level === 2 || +this.orgLever === 2) {
        code = (this.cityData[xIndex] || {}).lever_code
      } else {
        code = (this.countyData[xIndex] || {}).lever_code
      }
      if (this.level > 3 || !code) {
        return
      }
      const params = {
        'service_id.eq': this.clientId,
        isBIQuery: 1,
        'lever_code.endlike': code,
        'region_lever.eq': this.level + 1,
      }
      this.chart.showLoading()
      const [res, err] = await this.fetchData(params)
      this.chart.hideLoading()
      if (err) {
        return this.$message.error('请求数据失败，请重试！')
      }
      const xData = []
      const aData = []
      const bData = []
      if (res.data && this.level === 2) {
        this.countyData = res.data || []
      }
      ;(res.data || []).forEach(item => {
        xData.push(item.geo_name)
        aData.push(item.reply_total)
        bData.push(item.reply_funds)
      })
      this.setOption('分乡镇', xData, aData, bData)
      this.level++
    },
    async getData() {
      const params = {
        'service_id.eq': this.clientId,
        isBIQuery: 1,
        'region_lever.eq': this.orgLever + 1,
      }
      const [res, err] = await this.fetchData(params)
      this.cityData = res?.data ?? []
      if (err) {
        this.$message.error('请求数据失败，请重试！')
      }
      this.setCity()
    },
    fetchData(params) {
      return this.$utils.promise(this.$api.getData(this.$serviceName, this.tableName, params))
    },
    onback() {
      if (this.level === 4 && +this.orgLever === 1) {
        this.setCounty()
      } else {
        this.setCity()
      }
    },
    setCity() {
      // 不展示乡镇级别的数据（点击区县不下钻到乡镇） @唐文峰 2019-08-05
      // this.level = 0 改为 1，删除“返回区县”按钮
      this.level = this.orgLever + 1
      const xData = []
      const aData = []
      const bData = []
      this.cityData.forEach(item => {
        xData.push(item.geo_name)
        aData.push(item.reply_total)
        bData.push(item.reply_funds)
      })
      this.setOption('分区县', xData, aData, bData)
    },
    setCounty() {
      // 不展示乡镇级别的数据（点击区县不下钻到乡镇） @唐文峰 2019-08-05
      // this.level = 0 改为 1，删除“返回区县”按钮
      this.level = this.orgLever + 2
      const xData = []
      const aData = []
      const bData = []
      this.countyData.forEach(item => {
        xData.push(item.geo_name)
        aData.push(item.reply_total)
        bData.push(item.reply_funds)
      })
      this.setOption('分区县', xData, aData, bData)
    },
    setOption(subtext, xData, aData, bData) {
      this.option = {
        title: {
          text: '项目分布',
          show: false,
          subtext: subtext,
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: ['审批项目数', '审批金额'],
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        grid: {
          left: 50,
          right: 50,
        },
        xAxis: [
          {
            type: 'category',
            data: xData,
            axisLabel: {
              formatter: v => echartsXFormatter(v, 4),
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '数量(个)',
          },
          {
            type: 'value',
            name: '金额(万元)',
          },
        ],
        series: [
          {
            name: '审批项目数',
            type: 'bar',
            data: aData,
            label: { show: true, position: 'top', formatter: '{c}个' },
            barMaxWidth: 40,
          },
          {
            name: '审批金额',
            type: 'line',
            data: bData,
            label: { show: true, position: 'right', formatter: '{c}万元' },
            yAxisIndex: 1,
          },
        ],
      }
    },
  },
}
</script>
<style scoped>
.panel-title {
  position: relative;
  font-size: 1.142857rem;
}
</style>
